//
//  YsUploadManager+Tools.m
//  YsCloudFileManageSDK
//
//  Created by 宋宏康 on 2020/3/6.
//

#import "YsUploadManager+Tools.h"
#import "YsUploadManager+Private.h"
#import "NSArray+QMUI.h"
#import <YYKit/YYKit.h>

@implementation YsUploadManager (Tools)

- (void)checkUpload {
    SemaphoreBegin;
    NSInteger uploadloadingCount = 0;
    BOOL flag = YES;
    for (YsDocUploadModel *uploadModel in self.modelArray) {
        if (uploadModel.uploadStatus == 3) { /// 任务是正在上传的任务
            uploadloadingCount ++;
        }
        if (self.maxUploadTaskCount == 0) { /// 外面没有设置并发数，就用默认的并发数
            self.maxUploadTaskCount = kMAXUploadloadTASK_COUNT ;
        }
        
        if (uploadloadingCount >= self.maxUploadTaskCount) {
            flag = NO;
            break;
        }
    }
    NSLog(@"当前的下载数量是:%zd\n设置的最大并发数:%d",uploadloadingCount,self.maxUploadTaskCount);
    
    if (flag) { // 允许下载
        /// 按照等待的时间升序
        NSArray *resultNumArray = [self.modelArray sortedArrayUsingComparator:^NSComparisonResult(YsDocUploadModel* obj1, YsDocUploadModel *obj2) {
            NSNumber *num1 = [NSNumber numberWithString:obj1.waitTaskTime];
            NSNumber *num2 = [NSNumber numberWithString:obj2.waitTaskTime];
            return [num1 compare:num2]; // 升序 队列先进先出
        }];
        for (YsDocUploadModel *model in resultNumArray) {
            if (model.uploadStatus == 2) {// 当前的任务是等待
                if (self.maxUploadTaskCount == 0) {
                    self.maxUploadTaskCount = kMAXUploadloadTASK_COUNT;
                }
                if (self.maxUploadTaskCount - uploadloadingCount > 0) {
                    NSLog(@"开始上传任务了");
                    [self beginUploadWithUploadModel:model];
                    NSLog(@"执行过上传任务了");
                    uploadloadingCount ++;
                }else {
                    break;
                }
            }
        }
    }
    SemaphoreEnd;
}

- (void)uploadWithPath:(NSString *)uploadPath
              withPara:(NSString *)para
            withMethod:(NSString *)requestMethod
 withLastPathComponent:(NSString *)lastPathComponent
{
    SemaphoreBegin;
    NSParameterAssert(uploadPath);
    NSParameterAssert(lastPathComponent);
    [self _uploadWithPath:uploadPath withPara:para withMethod:requestMethod withLastPathComponent:lastPathComponent withIsMoveFile:YES];
    [self checkUpload];
    SemaphoreEnd;
}

- (void)uploadWithImage:(UIImage *)image
            withPara:(NSString *)para
          withMethod:(NSString *)requestMethod
withLastPathComponent:(NSString *)lastPathComponent
{
    SemaphoreBegin;
    NSParameterAssert(image);
    NSParameterAssert(lastPathComponent);
    NSString *imagePath =  [YsCloudFolderManager getPathToCacheImageWithAccountCode:kAccountCode withlastPathComponent:lastPathComponent withImage:image];
    [self _uploadWithPath:imagePath withPara:para withMethod:requestMethod withLastPathComponent:lastPathComponent withIsMoveFile:NO];
    [self checkUpload];
    SemaphoreEnd;
}

- (void)beginUploadWithUploadModel:(YsDocUploadModel *)uploadModel
{
    SemaphoreBegin;
    uploadModel.uploadStatus = 3;
    if (uploadModel.dataTask) {
        [self continueUploadWithModel:uploadModel];
    }else{
//        uploadModel.uploadedCount = 0;
        __block NSInteger i = uploadModel.uploadedCount;
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setValue:uploadModel.accountCode forKey:@"uid"];
        [parameters setValue:uploadModel.fileName forKey:@"name"];
        [parameters setValue:@(uploadModel.uploadedCount) forKey:@"chunk"];
        [parameters setValue:@(uploadModel.totalCount) forKey:@"chunks"];
        [parameters setValue:uploadModel.fileHash forKey:@"hash"];
            // 参数和接口
        NSString *requestUrl = kSuperUploadTestUrl;
#if 1
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//        NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:NSString.backgroundSessionIdentifier];
//           AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
            manager.responseSerializer.acceptableContentTypes= [NSSet setWithObjects:@"text/html", nil];
#else
        AFHTTPSessionManager *manager = self.manager;

#endif
        NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:uploadModel.filePath];
        [handle seekToFileOffset:0];
        NSData *blockData = [handle readDataOfLength:kSuperUploadBlockSize];
        [handle closeFile];
        NSLog(@"当前上传的切片数---:%zd",uploadModel.uploadedCount);
        
         
#if 1
        NSURLSessionDataTask *dataTask =
        [manager POST:requestUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            SemaphoreBegin;
            [formData appendPartWithFileData:blockData name:@"file" fileName:uploadModel.fileName mimeType:@"application/octet-stream"];
            SemaphoreEnd;
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            SemaphoreBegin;
            /// 上传完成
            if (uploadModel.uploadedCount == uploadModel.totalCount - 1){
                [self uploadFinishWithModel:uploadModel];
            }else{
                i ++;
                uploadModel.uploadedCount = i;
                [self continueUploadWithModel:uploadModel];
            }
            SemaphoreEnd;
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            SemaphoreBegin;
            uploadModel.uploadStatus = 6;
            [NSNotificationCenter.defaultCenter postNotificationName:kuploadError object:nil];
            SemaphoreEnd;
        }];
#else
    
        
#endif
        
        uploadModel.dataTask = dataTask;
    }
    SemaphoreEnd;
}

- (void)suspendTaskWithUploadModel:(YsDocUploadModel *)model
{
    SemaphoreBegin;
    NSParameterAssert(model);
    [model.dataTask suspend];
    model.uploadStatus = 5;
    [NSNotificationCenter.defaultCenter postNotificationName:kuploadSuspend object:nil];
    SemaphoreEnd;
}

- (void)cancelTaskWithUploadModel:(YsDocUploadModel *)model
{
    SemaphoreBegin;
    NSParameterAssert(model);
    [model.dataTask cancel];
    [NSNotificationCenter.defaultCenter postNotificationName:kuploadCancel object:nil];
    SemaphoreEnd;
}

- (void)resumeTaskWithUploadModel:(YsDocUploadModel *)model
{
    SemaphoreBegin;
    NSParameterAssert(model);
#if 0
    model.uploadStatus = 3;
    if (model.dataTask) {
        [model.dataTask resume];
    }else{
        [YsUploadManager.shareYsUploadManager continueUploadWithModel:model];
    }
#else
    
    model.waitTaskTime = [NSString stringWithFormat:@"%lld", [[YsCloudRealmTool getUploadTaskWaitTimeWhenTaskBeginWithAccountCode:kAccountCode] longLongValue] -1];
    NSInteger uploadMax = self.getCunrrentUploadMaxTaskCount;
    
    
    NSLog(@"xxxxxx");
    
    if (uploadMax == kMAXUploadloadTASK_COUNT) {
        /// 移除一个最后进入队列的下载任务
            NSArray *uploadingDaskArray =  [self.modelArray qmui_filterWithBlock:^BOOL(YsDocUploadModel *item) {
                 return item.uploadStatus == 3;
            }];
            /// 按照等待的时间升序
            NSArray *resultNumArray = [uploadingDaskArray sortedArrayUsingComparator:^NSComparisonResult(YsDocUploadModel* obj1, YsDocUploadModel *obj2) {
                NSNumber *num1 = [NSNumber numberWithString:obj1.waitTaskTime];
                NSNumber *num2 = [NSNumber numberWithString:obj2.waitTaskTime];
                return [num1 compare:num2]; // 升序 队列先进先出
            }];
        [self suspendTaskWithUploadModel:resultNumArray.lastObject];
    }
    
    model.uploadStatus = 2;
    [self checkUpload];
//    [NSNotificationCenter.defaultCenter postNotificationName:kuploadResume object:nil];
    
#endif
    SemaphoreEnd;
}


- (NSInteger)getCunrrentUploadMaxTaskCount
{
    SemaphoreBegin;
     NSInteger uploadingCount = 0;
     BOOL flag = YES;
     for (YsDocUploadModel *uploadModel in self.modelArray) {
         if (uploadModel.uploadStatus == 3) { /// 任务是正在下载的任务
             uploadingCount ++;
         }
         if (self.maxUploadTaskCount == 0) { /// 外面没有设置并发数，就用默认的并发数
             self.maxUploadTaskCount = kMAXUploadloadTASK_COUNT ;
         }
         
         if (uploadingCount >= self.maxUploadTaskCount) {
             flag = NO;
             break;
         }
     }
     NSLog(@"当前的上传数量是:%zd\n",uploadingCount);
    SemaphoreEnd;
    return uploadingCount;
}
@end



